package com.woniuxy.authserver.config;

import com.woniuxy.authserver.entity.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class TokenConfiguration {
    // 秘钥
    private static String SIGNING_KEY="www.woniuxy.com";

    // token转换器
    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = 
            new JwtAccessTokenConverter(){
                @Override
                public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {

                    final Map<String,Object> map = new HashMap<>();
                    // 从认证对象中得到用户信息
                    User user = (User) authentication.getUserAuthentication().getPrincipal();
                    // 将用户id放到token中
                    map.put("account",user.getAccount());
                    map.put("uid", user.getId());

                    ((DefaultOAuth2AccessToken)accessToken).setAdditionalInformation(map);
                    // 返回
                    return super.enhance(accessToken, authentication);
                }
            };

        jwtAccessTokenConverter.setSigningKey(SIGNING_KEY);
        return jwtAccessTokenConverter;
    }

    @Resource
    private DataSource dataSource;
    // 令牌存储策略:jwt方式
    // JdbcTokenStore：数据库存储token
    @Bean
    public TokenStore tokenStore(){
//        return new JwtTokenStore(accessTokenConverter());
        return new JdbcTokenStore(dataSource);
    }
}